package com.yanpp.tunte.test.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.framework.model.Member;
import org.framework.tunte.service.MemberService;
import org.framework.web.form.suport.GridDataBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/member")
public class MemberController {
	
	@Autowired
	MemberService memberService;
	
	@RequestMapping( method = RequestMethod.GET)
	public String list(Model model){
		List<Member> list=memberService.findAll();
		model.addAttribute("list", list);
		return "member/list";
	}
	
	@RequestMapping(params = "form", method = RequestMethod.POST)
	public String create(Member member,Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes){
		memberService.save(member);
		
		
		return "redirect:/member";
		
	}
	
	
	@RequestMapping(params = "form", method = RequestMethod.GET)
    public String createForm(Model uiModel) {
		Member member = new Member();
        uiModel.addAttribute("member", member);
        return "member/create";
    }
	
	@RequestMapping(value = "/{id}", params = "form", method = RequestMethod.POST)
	public String update(Member member,Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes){
		memberService.save(member);
		return "redirect:/member";
	}
	
	
	@RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
	public String updateForm(Model uiModel,@PathVariable("id") Long id){
		
		uiModel.addAttribute("member", memberService.findById(id));
		
		return "member/update";
	}
	
	
	@RequestMapping(value = "/listgrid", method = RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public GridDataBuilder listGrid(){
		
		
		
		List<String> columns=new ArrayList<String>();
		columns.add("姓名");
		columns.add("年龄");
		
		GridDataBuilder result=new GridDataBuilder();
		result.setColumns(columns);
		result.setDataSource(memberService.findAll());
		
		
		return result;
		
	}
	
	

}
